﻿using System.Windows.Controls;
using Pfz.Factoring;

namespace Pfz.WpfControls
{
	[AutoRegisterInEditorFactory(typeof(object), true)]
	internal sealed class ObjectEditor:
		StackPanel,
		IEditor
	{
		
		public object Record
		{
			get
			{
				return DataContext;
			}
			set
			{
				DataContext = value;

				if (value != null)
				{
					var children = Children;
					children.Clear();
					foreach(var property in value.GetType().GetProperties())
					{
						var control = new PropertyBoundControl();
						control.PropertyBinding = new PropertyBinding{ Property = property };
						children.Add(control);
					}
				}
			}
		}

		public object ApplyChanges()
		{
			var record = Record;
			if (record == null)
				return null;

			PropertyBoundControl.ApplyToDataSource(record);
			return record;
		}
	}
}
